﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Apewer.Models
{

    /// <summary>虚拟流，不写入任何数据，读取数据时候全部置为 0x00。</summary>
    internal class VoidStream : Stream
    {

        private long length = 0L;
        private long position = 0L;

        /// <summary>此属性始终返回 True。</summary>
        public override bool CanRead { get { return true; } }

        /// <summary>此属性始终返回 True。</summary>
        public override bool CanSeek { get { return true; } }

        /// <summary>此属性始终返回 True。</summary>
        public override bool CanWrite { get { return true; } }

        /// <summary>可设置为任意值，默认为 0。</summary>
        public override long Length { get { return length; } }

        /// <summary>可设置为任意值，默认为 0。</summary>
        public override long Position
        {
            get { return position; }
            set
            {
                if (value < 0) position = 0L;
                else if (value > length) position = length;
                else position = value;
            }
        }

        /// <summary>不执行任何动作。</summary>
        public override void Flush() { }

        /// <summary>读取流（不向参数 buffer 写入数据）。</summary>
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (buffer == null) return 0;
            if (buffer.LongLength < 1L) return 0;
            if (offset < 0) return 0;
            if (count < 1) return 0;
            var c = offset + count > buffer.Length ? buffer.Length - offset : count;
            position += c;
            return c;
        }

        /// <summary></summary>
        public override long Seek(long offset, SeekOrigin origin)
        {
            switch (origin)
            {
                case SeekOrigin.Begin:
                    Position = offset;
                    break;
                case SeekOrigin.Current:
                    Position = position += offset;
                    break;
                case SeekOrigin.End:
                    Position = length + offset;
                    break;
            }
            return position;
        }

        /// <summary>指定流的长度，最小值为 0。</summary>
        public override void SetLength(long value)
        {
            length = value > 0L ? value : 0L;
        }

        /// <summary>写入流，实际不写入任何数据。</summary>
        public override void Write(byte[] buffer, int offset, int count)
        {
            if (buffer == null) return;
            if (count < 1) return;
            if (buffer.LongLength < 1L) return;

            var s = offset;
            var e = offset + count;
            if (length < e) length = e;
            position = e;
        }

    }

}
